import Input from '@/components/Input'
import NavBar from '@/components/NavBar'
import Textarea from '@/components/Textarea'
import { RootState } from '@/store'
import {
  clearAuth,
  editUserPhoto,
  editUserProfile,
  getUserProfile,
} from '@/store/action/user'
import { Profile } from '@/store/reducer/user'
import history from '@/utils/history'
import { removeTokenInfo } from '@/utils/storage'
import { DatePicker, Dialog, List, Popup, Toast } from 'antd-mobile'
import dayjs from 'dayjs'
import { useEffect, useRef, useState } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import styles from './index.module.scss'

export default function ProfileEdit() {
  type PopupBottom = {
    visible: boolean
    type: 'photo' | 'gender' | ''
  }

  type PopupRight = {
    visible: boolean
    type: 'name' | 'intro' | ''
  }

  const { profile } = useSelector((state: RootState) => state.user)

  const dispatch = useDispatch()

  useEffect(() => {
    dispatch(getUserProfile())
  }, [dispatch])

  const [popupBottom, setpopupBottom] = useState<PopupBottom>({
    visible: false,
    type: '',
  })

  const [popupRight, setPopupRight] = useState<PopupRight>({
    visible: false,
    type: '',
  })

  const popupClose = () => {
    setpopupBottom({ visible: false, type: '' })
    setPopupRight({ visible: false, type: '' })
  }

  const fileRef = useRef<HTMLInputElement>(null)

  const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    console.log(e.target.files)
    if (e.target.files) {
      const file = e.target.files[0]
      const fd = new FormData()
      fd.append('photo', file)
      dispatch(editUserPhoto(fd))
      popupClose()
    }
  }

  const handleUpdateProfile = async (data: Partial<Profile>) => {
    await dispatch(editUserProfile(data))
    //  提示
    Toast.show({ content: '修改成功' })
    popupClose()
  }

  // 表单：用于绑定授课组件的状态
  const [name, setName] = useState('')

  // 用于绑定个人简介
  const [intro, setIntro] = useState('')

  //
  const [pickerShow, setPickerShow] = useState(false)

  const popupRightOpen = (type: 'name' | 'intro') => {
    if (type === 'name') {
      setName(profile.name)
    } else if (type === 'intro') {
      setIntro(profile.intro)
    }
    setPopupRight({ visible: true, type })
  }

  const handleSubmit = () => {
    if (popupRight.type === 'name') {
      handleUpdateProfile({ name })
    } else if (popupRight.type === 'intro') {
      handleUpdateProfile({ intro })
    }
  }

  const handleKeyUp = (e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.key === 'Enter') handleSubmit()
  }

  const handleConfirm = (value: Date) => {
    const birthday = dayjs(value).format('YYYY-MM-DD')

    handleUpdateProfile({ birthday })
  }

  return (
    <div className={styles.root}>
      <div className="content">
        {/* 顶部导航栏 */}
        <NavBar>个人资料</NavBar>

        <div className="wrapper">
          {/* 列表一：显示头像、昵称、简介 */}
          <List className="profile-list">
            <List.Item
              onClick={() => setpopupBottom({ visible: true, type: 'photo' })}
              arrow
              extra={<img className="avatar" src={profile.photo} alt="" />}
            >
              头像
            </List.Item>

            <List.Item
              onClick={() => popupRightOpen('name')}
              arrow
              extra={profile.name}
            >
              昵称
            </List.Item>

            <List.Item
              arrow
              extra={<span className="intro">{profile.intro || '未填写'}</span>}
              onClick={() => popupRightOpen('intro')}
            >
              简介
            </List.Item>

            <List.Item
              onClick={() => setpopupBottom({ visible: true, type: 'gender' })}
              arrow
              extra={profile.gender === 0 ? '男' : '女'}
            >
              性别
            </List.Item>
            <List.Item
              arrow
              extra={profile.birthday}
              onClick={() => setPickerShow(true)}
            >
              生日
            </List.Item>
          </List>

          {/* 文件选择框，用于头像图片的上传 */}
          <input
            className="avatar-upload"
            onChange={(e) => handleFileChange(e)}
            type="file"
            ref={fileRef}
            accept=".png,.jpg"
          />
        </div>

        {/* 底部栏：退出登录按钮 */}
        <div className="logout">
          <button
            className="btn"
            onClick={() =>
              Dialog.confirm({
                header: '提示',
                content: '是否退出？',
                confirmText: '残忍退出',
                cancelText: '再想想',
                onConfirm: () => {
                  removeTokenInfo()
                  dispatch(clearAuth())
                  history.push('/login')
                  Toast.show({ content: '退出成功' })
                },
              })
            }
          >
            退出登录
          </button>
        </div>

        {/* 底部弹出层 */}
        <Popup
          visible={popupBottom.visible}
          position="bottom"
          bodyClassName="popup-bottom-list"
          onMaskClick={() => popupClose()}
        >
          {popupBottom.type === 'photo' ? (
            <>
              <div
                className="list-item"
                onClick={() => fileRef.current?.click()}
              >
                拍照
              </div>
              <div
                className="list-item"
                onClick={() => fileRef.current?.click()}
              >
                本地选择
              </div>
            </>
          ) : (
            <>
              <div
                className="list-item"
                onClick={() => handleUpdateProfile({ gender: 0 })}
              >
                男
              </div>
              <div
                className="list-item"
                onClick={() => handleUpdateProfile({ gender: 1 })}
              >
                女
              </div>
            </>
          )}

          <div className="list-item" onClick={() => popupClose()}>
            取消
          </div>
        </Popup>

        {/* 侧边弹出层 */}
        <Popup
          visible={popupRight.visible}
          position="right"
          bodyClassName="popup-right"
          //  不可见时卸载内容
          destroyOnClose
        >
          <NavBar
            onBack={() => popupClose()}
            right={
              <span className="geek-color" onClick={() => handleSubmit()}>
                提交
              </span>
            }
          >
            编辑用户信息
          </NavBar>
          <div className="edit-content">
            {popupRight.type === 'name' ? (
              <>
                <h3 className="edit-title">编辑昵称</h3>
                <Input
                  className="edit-input"
                  autoFocus
                  onChange={(e) => setName(e.target.value)}
                  value={name}
                  onKeyUp={(e) => handleKeyUp(e)}
                />
              </>
            ) : (
              <>
                <h3 className="edit-title">编辑简介</h3>
                <Textarea
                  placeholder="请输入个人简介"
                  autoFocus
                  value={intro}
                  onChange={(e) => setIntro(e.target.value)}
                />
              </>
            )}
          </div>
        </Popup>

        {/* 日期选择器 */}
        <DatePicker
          visible={pickerShow}
          max={new Date()}
          value={new Date(profile.birthday)}
          min={new Date('1900-1-1')}
          onClose={() => setPickerShow(false)}
          onConfirm={(value) => handleConfirm(value)}
        ></DatePicker>
      </div>
    </div>
  )
}
